<!doctype html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="../css/mui.min.css" rel="stylesheet" />
		<link rel="stylesheet" href="../css/animate.min.css" />
		<link rel="stylesheet" href="../css/main.css" />
	</head>

	<body class="home">

		<div id="pullrefresh">

			<!--标题栏-->
			<div class="titlebar">

				<span class="sitename">张大妈</span>
				<div class="search-bar" onclick="tosearch()">
					<img src="../imgs/search.png" />
					<span class="kw">月饼饼</span>
				</div>

				<img src="../imgs/light.png" onclick="help()" />

			</div>

			<!--选项卡-->
			<div class="tabbar-wrap">
				<div class="tabbar" id="tabbar">

				</div>
				<div class="plus-wrap" onclick="toCategory()">
					<span class="plus mui-icon mui-icon-bars"></span>
				</div>
			</div>

			<!--轮播图-->
			<div id="banner">

			</div>

			<!--快捷入口-->
			<div class="link-wrap">

				<div class="item" onclick="channelTap(1)">
					<div class="icon link1">榜</div>
					<div class="name">人气榜</div>
				</div>

				<div class="item" onclick="channelTap(2)">
					<div class="icon link2">9.9</div>
					<div class="name">9.9包邮</div>
				</div>

				<div class="item" onclick="channelTap(3)">
					<div class="icon link3">抢</div>
					<div class="name">咚咚抢</div>
				</div>

				<div class="item" onclick="channelTap(4)">
					<div class="icon link4">荐</div>
					<div class="name">小编力荐</div>
				</div>

			</div>

			<!--商品列表-->
			<div id="listview">

			</div>

			<!--返回顶部-->
			<span class="totop hide mui-icon mui-icon mui-icon-arrowup" id="totop" onclick="scrolltotop()"></span>

		</div>

		<!--选项卡模板-->
		<script type="text/html" id='tabTpl'>
			{{each catelist item idx}}
			<div class="tab-item {{currTab==idx?'active':''}}" data-idx='{{idx}}' onclick="tabTap(this)">
				{{item.main_name}}
			</div>
			{{/each}}
		</script>

		<!--轮播图列表-->
		<script type="text/html" id='bannerTpl'>
			<div class="mui-slider">
				<div class="mui-slider-group">
					{{each bannerlist item idx}}
					<div class="mui-slider-item" onclick="tosubject({{idx}})">
						 <img src="http://img.haodanku.com/{{item.app_image}}" />
					</div>
					{{/each}}
				</div>
			</div>
		</script>

		<!--商品列表模板-->
		<script type="text/html" id='goodsTpl'>
			{{each goodslist item idx}}
			<div class="goods-item {{idx%2==1?'right':''}}" data-idx='{{(pageIdx-1)*50+idx}}' onclick="goodsTap(this)">
				<img class="lazy" data-src="{{item.itempic}}_310x310.jpg" />
				<span class="title mui-ellipsis">{{item.itemtitle}}</span>
				<div class="price-wrap">
					<div class="itemendprice">￥{{item.itemendprice}}</div>
					<div class="itemprice">￥{{item.itemprice}}</div>
					<div class="itemsale">销量{{item.itemsale}}</div>
				</div>
			</div>
			{{/each}}
		</script>
		<script src="../js/mui.min.js"></script>
		<script type="text/javascript" src="../js/template-web.js"></script>
		<script type="text/javascript" src="../js/api.js"></script>
		<script type="text/javascript" src="../js/zepto113.js"></script>
		<script type="text/javascript" src="../js/lazyload.js"></script>
		<script type="text/javascript">
			mui.init({
				pullRefresh: {
					container: "#pullrefresh", //下拉刷新容器标识，querySelector能定位的css选择器均可，比如：id、.class等
					down: {
						style: 'circle', //必选，下拉刷新样式，目前支持原生5+ ‘circle’ 样式
						color: '#FE413F', //可选，默认“#2BD009” 下拉刷新控件颜色
						height: '50px', //可选,默认50px.下拉刷新控件的高度,
						range: '100px', //可选 默认100px,控件可下拉拖拽的范围
						offset: '50px', //可选 默认0px,下拉刷新控件的起始位置
						auto: true, //可选,默认false.首次加载自动上拉刷新一次
						callback: function() { //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
							min_id = 1;
							getGoods();

							if (catelist.length == 0) {
								getCategory()
							}

							if (subgect.length == 0) {
								getSubject()
							}
						}
					},
					up: {
						height: 50, //可选.默认50.触发上拉加载拖动距离
						auto: false, //可选,默认false.自动上拉加载一次
						contentrefresh: "正在加载...", //可选，正在加载状态时，上拉加载控件上显示的标题内容
						contentnomore: '没有更多数据了', //可选，请求完毕若没有更多数据时显示的提醒内容；
						callback: function() { //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
							getGoods();
						}
					}
				},
			})

			mui.plusReady(function() {

				plus.webview.currentWebview().setStyle({
					scrollIndicator: 'none'
				});

				getHostKey()

				setTimeout(function() {
					plus.navigator.closeSplashscreen();
				}, 2000)

			})

			var currTab = 0;
			var catelist = [];

			//分类接口
			function getCategory() {
				api.getCategory(function(res) {
					if (res.code == 1) {
						catelist = res['general_classify'];
						//分类数据缓存到本地
						plus.storage.setItem("general_classify", JSON.stringify(catelist))

						catelist.unshift({
							"cid": 0,
							"main_name": "精选"
						})
						renderTabbar();
					}
				})
			}

			//tab切换
			function tabTap(e) {
				currTab = e.dataset.idx
				renderTabbar();

				scrolltotop();
				min_id = 1;
				getGoods();
			}

			//跳转到所有分类页面
			function toCategory() {
				var mainPageId = plus.storage.getItem('MainPageID');
				var mainPage = plus.webview.getWebviewById(mainPageId);
				mui.fire(mainPage, 'toCategory');
			}

			//重新渲染选项卡视图
			function renderTabbar() {
				var html = template('tabTpl', {
					catelist: catelist,
					currTab: currTab
				})
				document.getElementById('tabbar').innerHTML = html
			}

			//专题（banner）
			var subgect = []

			function getSubject() {
				api.getSubject(function(res) {
					if (res.code == 1) {
						subgect = res.data
						var html = template('bannerTpl', {
							bannerlist: subgect
						})
						$('#banner').html(html)

						var banner = mui('#banner');
						banner.slider({
							interval: 3000
						})
					}
				})
			}

			function tosubject(idx) {
				var item = subgect[idx]
				if (item) {
					mui.openWindow({
						url: "subject.html",
						name: "subject",
						extras: {
							title: item.name,
							sid: item.id
						}
					})

				}
			}

			//商品列表
			var pageCount = 50;
			var nomore = false;
			var min_id = 1; //页码（默认1 后续接口返回）
			var goodslist = []
			var pageIdx = 1

			function getGoods() {
				var params = {
					nav: 1,
					cid: 0,
					back: pageCount,
					min_id: min_id
				}
				if (catelist && catelist[currTab]) {
					params["cid"] = catelist[currTab]["cid"]
				}

				api.getGoods(params, function(res) {
					if (res.code == 1) {

						var list = res['data']
						nomore = list.length < pageCount
						if (min_id == 1) {
							goodslist = []
							pageIdx = 1
						} else {
							pageIdx++
						}

						//仅用于缓存(点击跳转详情)
						goodslist = goodslist.concat(list)

						var html = template('goodsTpl', {
							goodslist: list,
							pageIdx: pageIdx
						})

						if (pageIdx == 1) {
							$('#listview').html(html)
						} else if (pageIdx > 1 && list.length > 0) {
							$('#listview').append(html)
						}

						min_id = res['min_id']

						myLazyLoad.update()
					}

				})

				if (pageIdx == 1 && mui('#pullrefresh').pullRefresh()) {
					mui('#pullrefresh').pullRefresh().endPulldown();
				}
				if (mui('#pullrefresh').pullRefresh()) {
					mui('#pullrefresh').pullRefresh().endPullupToRefresh(nomore);
				}
			}

			function goodsTap(e) {
				var idx = e.dataset['idx']
				if (goodslist[idx] && window.plus) {
					mui.openWindow({
						url: 'detail.html',
						id: 'detail',

						styles: {
							popGesture: "close"
						},
						extras: {
							goods: goodslist[idx]
						}
					})
				} else {
					plus.nativeUI.alert('出错了')
				}

			}

			//搜索关键词
			function getHostKey() {
				if (!window.plus) {
					return
				}

				api.getHotkey(function(res) {
					if (res.code == 1) {
						var hotkey = res.data;

						if (hotkey) {
							console.log(hotkey[0]["keyword"])
							$(".kw")[0].innerHTML = hotkey[0]["keyword"]
							plus.storage.setItem("hotkey", JSON.stringify(hotkey))
						}
					}

				})

			}

			function tosearch() {
				console.log("===tosearch===")
				mui.openWindow({
					url: "search.html",
					id: "search",
					styles: {
						popGesture: "close"
					}
				})
			}

			//返回顶部

			function totopIn() {
				var totopview = document.getElementById("totop")
				totopview.classList.remove('hide')
				totopview.classList.add('fadeInUp', 'animated')
				totopview.addEventListener('animationend', totopInCallBack)
			};

			function totopInCallBack() {
				var totopview = document.getElementById("totop")
				totopview.classList.remove('fadeOutDown', 'animated')
				totopview.removeEventListener('animationend', totopInCallBack)
			}

			function totopOut() {
				var totopview = document.getElementById("totop")
				totopview.classList.add('fadeOutDown', 'animated')
				totopview.addEventListener('animationend', totopOutCallBack)
			};

			function totopOutCallBack() {
				var totopview = document.getElementById("totop")
				totopview.classList.remove('fadeOutDown', 'animated')
				totopview.classList.add('hide')
				totopview.removeEventListener('animationend', totopOutCallBack)
			}

			var totop = false;
			var scrollTop = 0;
			window.onscroll = function() {
				scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
				if (scrollTop > 1500 && !totop) {
					totop = true;
					totopIn()
				} else if (scrollTop < 500 && totop) {
					totop = false;
					totopOut()
				}
			}

			function scrolltotop() {
				window.scrollTo({
					top: 0,
					behavior: "smooth"
				})
			}

			//跳转领券教程
			function help() {
				mui.openWindow("help.html")
			}

			//快捷入口
			function channelTap(channelIdx) {

				switch (channelIdx) {
					case 1:
						mui.openWindow({
							url: 'top100.html',
							id: 'top100',
							styles: {
								popGesture: "close"
							}
						})
						break;
					case 2:
						mui.openWindow({
							url: 'nine.html',
							id: 'nine',
							styles: {
								popGesture: "close"
							}
						})
						break;
					case 3:
						var mainPageId = plus.storage.getItem('MainPageID');
						var mainPage = plus.webview.getWebviewById(mainPageId);
						mui.fire(mainPage, 'toDDQ');
						break;
					case 4:
						mui.openWindow({
							url: 'chosen.html',
							id: 'chosen',
							styles: {
								popGesture: "close"
							}
						})
						break;
				}

			}

			//图片懒加载器
			var myLazyLoad = new LazyLoad({
				elements_selector: ".lazy"
			});
		</script>
	</body>

</html>
